package ru.bytedog.oiot.counter.bot.service.adapter;

import com.google.gson.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import ru.bytedog.oiot.counter.bot.util.LocaleUtils;

import java.lang.reflect.Type;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Optional;

@Service
public class LocalDateTimeAdapter implements JsonSerializer<LocalDateTime>, JsonDeserializer<LocalDateTime> {

    public static final DateTimeFormatter DESERIALIZE = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
            .localizedBy(LocaleUtils.getLocale());
    public static final DateTimeFormatter SERIALIZE = DateTimeFormatter.ofPattern("dd MMMM HH:mm")
            .localizedBy(LocaleUtils.getLocale());

    @Override
    public LocalDateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        return Optional.ofNullable(json)
                .map(JsonElement::getAsString)
                .filter(StringUtils::isNotBlank)
                .map(value -> LocalDateTime.parse(value, DESERIALIZE))
                .orElse(null);
    }

    @Override
    public JsonElement serialize(LocalDateTime src, Type typeOfSrc, JsonSerializationContext context) {
        return Optional.ofNullable(src)
                .map(value -> value.format(SERIALIZE))
                .map(JsonPrimitive::new)
                .orElse(null);
    }
}
